package com.hzdp.netty.aio;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.Date;

import org.apache.log4j.Logger;

public class ReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {

	protected static Logger logger = Logger.getLogger(ReadCompletionHandler.class);

	private AsynchronousSocketChannel channel;

	public ReadCompletionHandler(AsynchronousSocketChannel channel) {
		if (this.channel == null) {
			this.channel = channel;
		}
	}

	@Override
	public void completed(Integer result, ByteBuffer attachment) {
		attachment.flip();
		byte[] body = new byte[attachment.remaining()];
		attachment.get(body);

		try {
			String req = new String(body, "UTF-8");
			logger.info("The Time Server receive order :" + req);
			String currentTime = new Date().toString();
			doWrite(currentTime);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void doWrite(String currentTime) throws IOException {
		byte[] bytes = currentTime.getBytes();
		ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
		writeBuffer.put(bytes);
		writeBuffer.flip();
		channel.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() {

			@Override
			public void completed(Integer result, ByteBuffer buffer) {
				if (buffer.hasRemaining()) {
					channel.write(buffer, buffer, this);
				}
			}

			@Override
			public void failed(Throwable exc, ByteBuffer attachment) {
				logger.error(exc, exc);
				try {
					channel.close();
				} catch (IOException e) {
					logger.error(e, e);
				}
			}
		});
	}

	@Override
	public void failed(Throwable exc, ByteBuffer attachment) {
		logger.error(exc, exc);
		try {
			channel.close();
		} catch (IOException e) {
			logger.error(e, e);
		}
	}

}
